/*
 * Copyright (c) 2021
 * User:魔金多商户商城
 * File:AppletsLoginUtils.java
 * Date:2020/11/27 16:26:27
 */

package com.ruoyi.appletsutil;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Rediskey;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.tc.domain.TcMember;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 小程序登录工具类
 *
 * @author SK
 * @since 2018/6/13
 */
public class AppletsLoginUtils {
    private static AppletsLoginUtils ourInstance = new AppletsLoginUtils();


    private AppletsLoginUtils() {
    }

    public static AppletsLoginUtils getInstance() {
        return ourInstance;
    }

    /**
     * 获得用户id
     *
     * @return 返回用户id
     */
    public long getCustomerId(HttpServletRequest request) {
        long customerId = 0;
        if (!ObjectUtils.isEmpty(getClaims(getToken(request)))) {
            customerId = getClaims(getToken(request)).getId();
        }
        return customerId;
    }

    /**
     * 获得用户id
     *
     * @return 返回用户id
     */
    public TcMember getCustomer(HttpServletRequest request) {
        return getClaims(getToken(request));
    }

    /**
     * 获取token
     *
     * @param request request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        // 认证信息在header 中的key
        final String authHeader = request.getHeader("Authorization");

        if (Objects.isNull(authHeader) || !authHeader.startsWith("Bearer")) {
            return null;
        }
        return authHeader.length() >= 7 ? authHeader.substring(7) : authHeader.substring(6);
    }

    /**
     * 获取小程序凭证实体
     *
     * @param token token
     * @return 小程序凭证实体
     */
    private TcMember getClaims(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String claims = SpringUtils.getBean(RedisCache.class).getValue(String.format(Rediskey.TOKEN, token));
        return StringUtils.isEmpty(claims) ? null : JSONObject.parseObject(claims, TcMember.class);
    }

    /**
     * 获得用户id
     *
     * @return 返回用户id
     */
    public long getSessionCustomerId(HttpServletRequest request) {
        long customerId = 0;
        TcMember member = (TcMember) request.getSession().getAttribute("user");
        if (member != null && member.getId() > 0) {
            customerId = member.getId();
        }
        return customerId;
    }

    /**
     * 获得用户id
     *
     * @return 返回用户id
     */
    public TcMember getSessionCustomer(HttpServletRequest request) {
        return (TcMember) request.getSession().getAttribute("user");
    }
}
